package com.lysh.http.handler;

import com.lysh.http.api.API;
import com.lysh.http.exception.SDKException;
import com.lysh.http.utils.JsonUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @author liyishan
 * @date 2023/4/19 12:59
 */

public class Executor {
    private static final Logger log = LoggerFactory.getLogger(Executor.class);
    public CloseableHttpClient httpClient;

    public Executor() {
    }

    public String execute(CloseableHttpClient httpClient, API api) throws SDKException {
        this.httpClient = httpClient;
        String json = JsonUtils.toJson(api.getAPIParams());
        StringEntity entity = new StringEntity(json, Charset.forName("UTF-8"));
        HttpPost post = new HttpPost(api.getUrl());
        Map<String, String> addHeaders = api.getHeaders();
        if (!CollectionUtils.isEmpty(addHeaders)) {
            addHeaders.forEach((k, v) -> {
                post.setHeader(k, v);
            });
        }
        post.setEntity(entity);
        String returnStr = "";
        try {
            CloseableHttpResponse response = httpClient.execute(post);
            returnStr = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
        } catch (IOException var8) {
            log.error("POST 请求失败 url:{},param:{} e:", new Object[]{api.getUrl(), JsonUtils.toJson(api.getAPIParams()), var8});
        }

        return returnStr;
    }

}
